package tools

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm/logger"
	"os"
	"time"
)

type ImageType struct {
	gorm.Model
	ImageName  string
	ImageAlias string
}


var DB *gorm.DB

// 定义自己的 db Writer
type MyWriter struct {
	mlog *logrus.Logger
}

// 实现gorm/logger.Writer接口
func (m *MyWriter)Printf(format string , v ...interface{}){
	logstr  := fmt.Sprintf(format, v...)
	// 利用loggus记录日志
	m.mlog.Info(logstr)
}

func NewMyWriter() *MyWriter{
	log := logrus.New()
	//配置logrus
	log.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat:"2006-01-02 15:04:05",
	})

	f, err := os.OpenFile("logs/db.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)

	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "NewMyWriter",
		}).Warn(err)
	}

	log.Out = f
	log.Level = logrus.InfoLevel // 设置日志级别
	return &MyWriter{mlog:log}
}


func InitDB() (*gorm.DB, error){
	slowLogger := logger.New(
		//设置Logger
		NewMyWriter(),
		logger.Config{
			//慢SQL阈值
			SlowThreshold: time.Millisecond,
			//设置日志级别，只有Warn以上才会打印sql
			LogLevel:      logger.Warn,
		},
	)

	DB, err := gorm.Open(sqlite.Open("./logs/mondo.db"), &gorm.Config{
		Logger:slowLogger,
	})
	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "InitDB",
		}).Warn(err)
		return DB, err
	}

	// Migrate the schema
	DB.AutoMigrate(&ImageType{})

	return DB, nil
}

// 将下载镜像名以及镜像别名写入至数据库
func WriteImageDB(imageSourceName, imageAliaseName string) error{
	db, err := InitDB()
	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "WriteImageDB",
		}).Warn(err)
		return err
	}

	db.Create(&ImageType{ImageName: imageSourceName, ImageAlias: imageAliaseName})
	return  nil
}


// 下载时查询镜像是否出现重新下载
func CheckImagePull(imageSourceName string) (int, error){
	db, err := InitDB()
	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "CheckImagePull",
		}).Warn(err)

		return 0, err
	}

	result := db.Where("image_name = ?", imageSourceName).First(&ImageType{})

	// fmt.Println("查询镜像信息：", result,"   ", result.RowsAffected)
	if result.RowsAffected == int64(1) {
		return 1, nil
	}

	return 0, err
}

// 上传查询镜像是否出现重新下载
func CheckImagePush(imageSourceName string) (int, error){
	db, err := InitDB()
	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "CheckImagePush",
		}).Warn(err)
		return 0, err
	}

	result := db.Where("image_alias = ?", imageSourceName).First(&ImageType{})

	// fmt.Println("查询镜像信息：", result,"   ", result.RowsAffected)
	if result.RowsAffected == int64(1) {
		return 1, nil
	}

	return 0, err
}

// 上传查询镜像是否出现重新下载
func CheckImageName(imageSourceName string) (string, error){
	it := ImageType{}
	db, err := InitDB()
	if err != nil {
		Log.WithFields(logrus.Fields{
			"msg": "CheckImageName",
		}).Warn(err)
		return "", err
	}

	db.Select("image_alias").Where("image_name = ?", imageSourceName).Find(&it)
	returImageName := it.ImageAlias

	return returImageName, nil
}


// 从数据库中查询已有镜像
func ListImageDb() []ImageType{
	var poolname []ImageType
	db, _ := InitDB()
	db.Select("image_name", "image_alias").Find(&poolname)

	return poolname
}